<script setup name="name">
import * as echarts from 'echarts'
import { nextTick } from 'vue'
const props = defineProps({
  data: {
    type: Array,
    default: () => []
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '400px'
  },
  borderRadius: {
    type: String || Number,
    default: 10
  },
  tooltipShow: {
    type: Boolean,
    default: true
  },
  legendShow: {
    type: Boolean,
    default: true
  },
  fontSize: {
    type: Number,
    default: 10
  },
  xh: {
    type: Boolean,
    default: true
  }
})
// 线边仓实例
const lineEdgeRef = ref(null)

const myChart = ref()
const option = {
  tooltip: {
    trigger: 'item'
  },
  legend: {
    top: '30%',
    left: '70%',
    textStyle: {
      color: '#fff'
    }
  },
  // echarts固定高度
  grid: {
    containLabel: true
  },
  series: [
    {
      left: '-15%',
      data: [],
      label: {
        normal: {
          show: true,
          position: 'outside',
          color: '#fff',
          formatter: params => {
            return params.data.name + ' ' + params.data.value
          }
          //自定义显示格式(b:name, c:value, d:百分比)
        }
      },
      type: 'pie',
      radius: '50%',
      name: '数量'
    }
  ]
}
let tiemr = null
const initData = () => {
  clearInterval(tiemr)
  option.series[0].data = props.data
  // 初始化echart
  const chartRefWrap = unref(lineEdgeRef)
  if (chartRefWrap) {
    myChart.value = echarts.init(chartRefWrap)

    myChart.value.setOption(option)
    window.addEventListener('resize', chartsResize)
    //自动切换顺序
    var cityIndex = 0
    if (!props.xh) return
    tiemr = setInterval(function () {
      if (cityIndex < props.data.length) {
        init(cityIndex)
        cityIndex++
      } else {
        cityIndex = 0
        init(cityIndex)
        cityIndex++
      }
    }, 1000)
  }
}

// 动态
const init = cityIndex => {
  myChart.value.dispatchAction({ type: 'downplay', seriesIndex: 0 })
  myChart.value.dispatchAction({ type: 'highlight', seriesIndex: 0, dataIndex: cityIndex })
  myChart.value.dispatchAction({ type: 'showTip', seriesIndex: 0, dataIndex: cityIndex })
}

const chartsResize = () => {
  myChart.value && myChart.value.resize()
}

nextTick(() => {
  initData()
})

watch(
  () => props.data,
  val => {
    if (val.length > 0) {
      setTimeout(() => {
        initData()
      }, 1000)
      initData()
    }
  },
  {
    deep: true,
    immediate: true
  }
)
</script>

<template>
  <div ref="lineEdgeRef" :style="{ width: props.width, height: props.height }"></div>
</template>

<style lang="scss" scoped>
.ss {
  background-color: red;
}
</style>
